#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" photofile.ru plugin """

import sys
import os
import re
import urllib

__all__ = ["VERSION", "NAME", "TITLE",
           "album_list_uri", "parse_album_list", "album_list_page_uri",
           "parse_photo_list"]

VERSION = "0.0.0.1"
NAME = "photofile.ru"
TITLE = u"Фото на photofile.ru"

RE_ALBLIST = re.compile(ur'<div\s+.*?class=".*?alb_name".*?<a\s+href\s*=\s*"(?P<href>.*?)\".*?>(?P<title>.*?)</a>', re.U|re.I|re.S|re.M)

def album_list_uri(user, **kwargs):
    """Make album list uri for specified user.

    returns:
        dict
    """
    r = {
        'url': 'http://photofile.ru/users/%s/?page=1&act=change&pass_on=1' % (urllib.quote(user.encode('utf-8')),),
        'multipage': True,
        'page': 1,
        'user': user
    }
    return r

def album_list_page_uri(user, page, **kwargs):

    r = kwargs or {}
    r['url'] = 'http://photofile.ru/users/%s/?order=modified&pass_on=&page=%s' % (user, page)
    r['user'] = user
    r['page'] = page
    return r

def parse_album_list(html, **kwargs):
    """
    Returns dict of kwargs +

    `next_page` : str
        URI for next page if present
    `multipage` : bool
        True if next page available
    `albums` : list-of-tuple
        (url, title, image-count) per album entry
    """

    ret = kwargs or {}
    ret['albums'] = []

    #print "WRITE HTML"
    #with open("album_list_%s.html" % (kwargs.get('user', ''),), "w") as f:
    #    f.write(html.encode('utf-8'))

    ret['albums'].extend([('http://photofile.ru/%s/rss' % (x[0],), x[1], '') for x in RE_ALBLIST.findall(html) if x])

    ss = u'<a\\s+href=".*?/users/%s/\\?.*?&page=(\\d+).*?>' % (kwargs.get('user', ''),)
    re_pg = re.compile(ss, re.I|re.S|re.U)
    pgs = set([int(x) for x in re_pg.findall(html)])
    try:
        page = int(kwargs.get('page', 0))
    except:
        page = 1
    #print "PGS", pgs, ss
    a = kwargs.copy()
    if 'user' in a: a.pop('user')
    if 'page' in a: a.pop('page')
    if pgs:
        ret['multipage'] = True
        ret['page_count'] = int(max(pgs))
        if page < ret['page_count']:
            ret['next_page'] = album_list_page_uri(kwargs['user'], page+1, **a)['url']
        else:
            ret['next_page'] = ''
        ret['page'] = page + 1
        print "MULTIPAGE:", ret['page_count'], " <== ", pgs

    return ret

def parse_photo_list(rss, **kwargs):

    #print "WRITE HTML"
    #with open("photo_list_%s.html" % (kwargs.get('user', ''),), "w") as f:
    #    f.write(html.encode('utf-8'))

    RE_PH = re.compile(ur'<item>\s*<title>(?P<title>.*?)</title>\s*<link>.*?(?P<album>[^/]+?)/(?P<img>[^/]+?)/#.*?</link>', re.I|re.U|re.M|re.S)
    phs = RE_PH.findall(rss)
    r = []
    loc = {}
    loc.update(kwargs)

    for title, alb, img in phs:
        loc['alb'] = alb
        loc['title'] = title
        loc['img'] = img
        r.append({
            'title': u"%s (%s)" % (title, img),
            'full': 'http://%(user)s.users.photofile.ru/photo/%(user)s/%(alb)s/%(img)s.jpg' % loc,
            'thumb': 'http://photofile.ru/photo/%(user)s/%(alb)s/small/%(img)s.jpg' % loc,
            'medium': 'http://photofile.ru/photo/%(user)s/%(alb)s/%(img)s/' % loc,
            }
        )
    ret = kwargs
    ret['photos'] = r
    return ret

if __name__ == "__main__":
    pass
